var api = require('../config/api.js');
const app = getApp()

//时间格式
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


//检测token时效性
function tokenTime() {
  var currentTime = formatTime(new Date)
  wx.setStorageSync('cacheTime', currentTime)
  var cacheTime = wx.getStorageSync('cacheTime');
  var cacheTime = (new Date(cacheTime)).getTime();
  var currentTime = (new Date(currentTime)).getTime();
  var time = parseInt(currentTime - cacheTime)
  if (time > 518400000) {  //重新登录
    App.login()
  } else {  //重新缓存时间
    wx.setStorageSync('cacheTime', currentTime)
  }
}


//封装微信的request
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Nideshop-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        //console.log("success");
        if (res.statusCode == 200) {
          resolve(res)
        } else {
          reject(res);
        }

      },
      fail: function (err) {
        //console.log("fail")
        reject(err)
      }
    })
  });
}



module.exports = {
  formatTime: formatTime,
  tokenTime,
  request
}
